#include "crfTestImp0.h"


crfTestImp0::crfTestImp0(void)
{
	_feature_num_all=0;
	_temp_space.set_size(80*1024);
	_lambda=0;
	_temfea = 0;

}


crfTestImp0::~crfTestImp0(void)
{
	if(_lambda) delete[](_lambda);
}

void crfTestImp0::WritetoFile(sentence& sen, vector< vector<int> >& predict_labels,vector< vector<double> >& predict_prob,double fvalue,FILE* fod)
{
	fprintf(fod,"%.8f:\t",fvalue);
	for(int i=0;i<predict_labels.size();i++)
	{
		int idorg = sen.labels[i];
		if(idorg!=-1)
			fprintf(fod,"%s_",_temfea->_labels[idorg].c_str());
		else
			fprintf(fod,"NONE_");

		int it;
		for(it =0;it<predict_labels[i].size()-1;it++)
		{
			int idpr = predict_labels[i][it];
			double p = predict_prob[i][it];
			if(idpr!=-1)
				fprintf(fod,"%s/%.5f_",_temfea->_labels[idpr].c_str(),p);
			else
				fprintf(fod,"NONE_");
		}
		int idpr = predict_labels[i][it];
		double p = predict_prob[i][it];
		if(idpr!=-1)
			fprintf(fod,"%s/%.5f\t",_temfea->_labels[idpr].c_str(),p);
		else
			fprintf(fod,"NONE\t");
		
	}
	fprintf(fod,"\n");
}

void crfTestImp0::Test(char *fea_file,char* lambda_file,vector<string> testfiles,char* outfile)
{
	_temfea = new TempleteFea(1,10);
	_temfea->load_model(fea_file,true);
	_feature_num_all= _temfea->_feature_num;
	_lambda = new double[_feature_num_all];
	memset(_lambda,0,_feature_num_all*sizeof(double));
	ReadBinDouble(lambda_file,_feature_num_all,_lambda);

	_foMst._tag_size = _temfea->_tag2idx.size()+1;
	_foMst._lambda = _lambda;
	_foMst._gradient = 0;
	int begin_id = _temfea->get_label_index((string)"0o");
	assert_loc(begin_id!=-1);
	_foMst._tag_sentence_begin = begin_id+1;
	int _lambda_size = _feature_num_all;

	vector<sentence> sen_pooltrain;
	memPool<char> vec_pools;
	FILE* fod = fopen(outfile,"wb");
	int error_num = 0;
	int total_num = 0;
	for (int ibatch=0;ibatch<testfiles.size();ibatch++)
	{
		printf("@begin handle %d\n",ibatch);
		read_senbin((char*)testfiles[ibatch].c_str(),sen_pooltrain,vec_pools);
		//-------
		for (unsigned int isen=0;isen<sen_pooltrain.size();isen++) {
			vector< vector<int> > predict_labels;
			vector< vector<double> >predict_prob;
			double fvalue = _foMst.process_decode(sen_pooltrain[isen],predict_labels,predict_prob);
			WritetoFile(sen_pooltrain[isen],predict_labels,predict_prob,fvalue,fod);

			for(int i=0;i<predict_labels.size();i++)
			{
				if(predict_labels[i][0]!=sen_pooltrain[isen].labels[i])
					error_num++;
				total_num++;
			}

			cout<<"done["<<isen<<"]job|len="<<sen_pooltrain[isen].l<<"["<<fvalue<<","<<error_num/(float)total_num<<"]...";
		}
		//-------
		printf("\n@end handle %d>>>\n",ibatch);
		//-------
		sen_pooltrain.clear();
		//-------
	}
	fprintf(fod,"RES: %d ,%d, %.9f\n",error_num,total_num,error_num/(float)total_num);
	fclose(fod);
}